"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 主节点获取X锁，备节点获取S锁，锁冲突，等待锁超时释放锁
Create At   : 2023/07/20
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on,设置锁超时参数
    2.创建测试表
    3.主节点获取X锁，不提交
    4.备节点获取S锁
    5.清理环境
Expect      :
    1.成功
    2.执行成功
    3.成功
    4.阻塞，锁超时报错
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table = 't_multi_node_write_0074'
        self.para_time = dict()
        self.paras = dict()
        self.paras['enable_remote_execute'] = self.common.show_param(
            'enable_remote_execute')
        self.paras['allow_concurrent_tuple_update'] = self.common.show_param(
            'allow_concurrent_tuple_update')
        self.para_time['update_lockwait_timeout'] = self.common.show_param(
            'update_lockwait_timeout')
        self.para_time['lockwait_timeout'] = self.common.show_param(
            'lockwait_timeout')

    def test_dms_ock(self):
        text1 = '-----step1:修改enable_remote_execute参数值为on，设置锁超时参数;expect:成功-----'
        self.log.info(text1)
        for key in self.para_time.keys():
            guc_res = PrimarySh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG, f'{key}=10s')
            self.log.info(guc_res)
            self.assertTrue(guc_res, f"设置{key}失败:{text1}")
        for key in self.paras.keys():
            guc_res = PrimarySh.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, f'{key}=on')
            self.log.info(guc_res)
            self.assertTrue(guc_res, f"设置{key}失败:{text1}")
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'重启集群失败:{text1}')

        text2 = '-----step2:创建测试表;expect:执行成功-----'
        self.log.info(text2)
        create_tb = f"drop table if exists {self.table} cascade;" \
                    f"create table {self.table}(" \
                    f"id int, name varchar, source number) with(segment=on);" \
                    f"insert into {self.table} values(1, 'haha', 92);"
        create_tb_res = PrimarySh.execut_db_sql(create_tb)
        self.log.info(create_tb_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_tb_res,
                      f"建表失败:{text2}")

        text3 = '-----step3:主节点获取X锁;expect:成功-----'
        self.log.info(text3)
        sql_a = f"start transaction;" \
                f"drop table {self.table};" \
                f"select pg_sleep(20)"
        session1 = ComThread(PrimarySh.execut_db_sql, args=(sql_a,))
        session1.setDaemon(True)
        session1.start()

        text4 = '-----step4:备节点获取S锁;expect:锁超时-----'
        self.log.info(text4)
        sql = f"begin;" \
              f"select * from {self.table};"
        res = self.standby_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn('ERROR:  SSLock wait timeout', res, f"执行失败:{text4}")
        session1.join(30)
        res_a = session1.get_result()
        self.log.info(f'session1_results: {res_a}')
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      res_a, f"执行失败:{text3}")
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res_a, f"执行失败:{text3}")

    def tearDown(self):
        text5 = '-----step5:清理环境 expect:成功-----'
        self.log.info(text5)
        drop_tb_res = PrimarySh.execut_db_sql(
            f"drop table if exists {self.table} cascade;")
        self.log.info(drop_tb_res)
        self.paras.update(self.para_time)
        for key, value in self.paras.items():
            res = PrimarySh.execute_gsguc(
                'reload', self.constant.GSGUC_SUCCESS_MSG, f'{key}={value}')
            self.log.info(res)
            self.assertTrue(res, f"恢复参数值失败:{text5}")
        self.assertIn(self.constant.DROP_TABLE_SUCCESS,
                      drop_tb_res, f"删表失败:{text5}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
